package org.example.service;

import jakarta.annotation.Resource;
import jakarta.transaction.Transactional;
import org.example.dao.ICartRepository;
import org.example.entity.Cart;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CartService { //service可以抽象成接口
    @Resource
    private ICartRepository cartRepository;

    public Cart addCart(String userId, String businessId, Integer foodId){
        Cart cart = new Cart();
        Cart cartTemp = cartRepository.findByUserIdAndBusinessIdAndFoodId(userId, Integer.valueOf(businessId),foodId);
        if(cartTemp != null){
            return cartTemp;
        }else{
            cart.setFoodId(foodId);
            cart.setUserId(userId);
            cart.setBusinessId(Integer.valueOf(businessId));
            cart.setQuantity(1);
            return cartRepository.save(cart);
        }

    }

    @Transactional
    public Cart updateQuantityByBidAndUidAndFid(String userId, Integer foodId, Integer businessId, Integer quantity) {
        Cart cartTemp = cartRepository.findByUserIdAndBusinessIdAndFoodId(userId, businessId,foodId);
        if(cartTemp!=null){
            cartRepository.updateQuantityByBidAndUidAndFid(userId, foodId, businessId, quantity);
            cartTemp.setQuantity(quantity);
            return cartTemp;
        }
        return null;
    }

    public List<Cart> findAllByUidOrByUidAndBid(String userId, String businessId){
        if(businessId==null){
            return cartRepository.findAllByUserId(userId);
        }else{
            return cartRepository.findAllByUserIdAndBusinessId(userId, Integer.valueOf(businessId));
        }
    }

    public void deleteByUidAndBidAndFidOrByUidAndBid(String userId, String businessId, Integer foodId){
        if(foodId == null){
            cartRepository.deleteAllByUserIdAndBusinessId(userId, Integer.valueOf(businessId));
        }else{
            cartRepository.deleteByUserIdAndBusinessIdAndFoodId(userId, Integer.valueOf(businessId), foodId);
        }
    }
}
